package ca.tatham.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
	private static final long START_NANO;
	private static final SimpleDateFormat FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss.");

	static {
		START_NANO = System.nanoTime();
	}

	public static void log(Object object, String message) {
		StringBuilder msg = new StringBuilder();
		String time = getTimeString();
		appendToLengthAtLeft(msg, time, 29);
		msg.append(' ');
		String threadName = Thread.currentThread().getName();
		appendToLengthAtLeft(msg, threadName, 10);
		msg.append(' ');
		appendToLengthAtLeft(msg, object.getClass().getSimpleName(), 12);
		msg.append(' ');
		msg.append(message);
		System.out.println(msg);
	}

	private static String getTimeString() {
		String string = FORMAT.format(new Date());
		long time = (System.nanoTime() - START_NANO) % 1000000000L;
		return string + time;
	}

	private static void appendToLengthAtLeft(StringBuilder buffer,
			String string, int length) {
		if (string.length() > length) {
			buffer.append(string.subSequence(0, length));
		} else {
			buffer.append(string);
			for (int i = string.length(); i < length; i++) {
				buffer.append('.');
			}
		}
	}

}
